const { verifyToken, generateToken } = require("../utils/jwt");
const auth = async (ctx, next) => {
    if (ctx.headers.authorization) {
        const token = ctx.headers.authorization.split(" ")[1] || "";
        if (verifyToken(token)) {
            // 验证通过，重新生成token，保证登录状态
            const username = verifyToken(token).username;
            ctx.set("Authorization", generateToken({ username }, "1h"));
            await next();
        } else {
            ctx.body = {
                code: 401,
                msg: "登录已过期，请重新登录",
            };
        }
    } else {
        ctx.body = {
            code: 401,
            msg: "登录已过期，请重新登录",
        };
    }
};

module.exports = auth;
